#include "../source/server.hpp"

//这里解决了之前的一个问题，之前的问题：客户端提前ctrl+c，服务器会崩溃，而现在不会了

//管理所有的连接
std::unordered_map<uint64_t, PtrConnection> _conns;
uint64_t conn_id = 0;

void ConnectionDestroy(const PtrConnection& conn)
{
    _conns.erase(conn->Id());
}
void OnConnected(const PtrConnection& conn)
{
    DBG_LOG("NEW CONNECTION:%p", conn.get());
}
void OnMessage(const PtrConnection& conn, Buffer* buf)
{
    DBG_LOG("%s", buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "Hello World";
    conn->Send(str.c_str(), str.size());
}

void Acceptor(EventLoop* loop, Channel* lst_channel)
{
    int fd = lst_channel->Fd();
    int newfd = accept(fd, NULL, NULL);
    DBG_LOG("获得一个新的连接");
    if (newfd < 0)
        return;
    conn_id++;
    PtrConnection conn(new Connection(loop, conn_id, newfd));
    //conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetMessageCallback(OnMessage);
    conn->SetSvrClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRealse(10); //启动非活跃超时销毁
    conn->Establised(); //就绪初始化
    _conns.insert(std::make_pair(conn_id, conn));
}

int main()
{
    srand(time(NULL));
    EventLoop loop;
    Socket lst_sock;
    bool ret = lst_sock.CreateServer(8085);
    //为监听套接字，创建一个Channel进行事件的管理，以及事件的处理
    Channel channel(&loop, lst_sock.Fd());//此时还是监听套接字
    channel.SetReadCallback(std::bind(Acceptor, &loop, &channel));//回调中，获取新连接，为新连接创建Channel并且添加监控
    // loop.UpdateEvent(&channel);
    channel.EnableRead();//启动监听的可读事件监控 -- 会自动将自己挂到poller中
    while (1)
    {
        loop.Start();
    }
    lst_sock.Close();
    return 0;
}